package axht.trade.android.storage;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

public class SdActivity extends AppCompatActivity {

    private EditText editName;

    private EditText editValue;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sd);
        editName = findViewById(R.id.edit_name);
        editValue = findViewById(R.id.edit_value);
    }


    /**
     * 将数据保存到/mnt/sdcard/下面
     * @param view
     */
    public void save1(View view) throws IOException {
        //判断是否拥有权限
        if(ContextCompat.checkSelfPermission(SdActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(SdActivity.this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
        }else{
            save1Method();
        }

    }

    public void save1Method() throws IOException {
        //保存数据到sdcard
        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            //1 获取sdcard存储路径
            File externalStorageDirectory = Environment.getExternalStorageDirectory();
            if(!externalStorageDirectory.exists()){
                externalStorageDirectory.mkdir();
            }
            String externalAbsolutePath = externalStorageDirectory.getAbsolutePath();
            //1.2 获取文件名和内容
            String fileName = editName.getText().toString();
            String fileContent = editValue.getText().toString();
            //1.3 保存
            String filePath = externalAbsolutePath+"/"+fileName;
            FileOutputStream fileOutputStream = new FileOutputStream(filePath);
            byte[] contentBytes = fileContent.getBytes();
            fileOutputStream.write(contentBytes);
            fileOutputStream.flush();
            fileOutputStream.close();
            Toast.makeText(this,"保存成功",Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 读取/mnt/sdcard/下面数据
     * @param view
     */
    public void read1(View view) throws IOException {
        //判断是否拥有权限
        if(ContextCompat.checkSelfPermission(SdActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(SdActivity.this,new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},2);
        }else{
            read1Method();
        }
    }


    public void read1Method() throws IOException {
        //读取sdcard数据
        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            //1 获取sdcard存储路径
            File externalStorageDirectory = Environment.getExternalStorageDirectory();
            if(!externalStorageDirectory.exists()){
                Toast.makeText(this,"文件夹不存在",Toast.LENGTH_SHORT).show();
                return;
            }
            String externalAbsolutePath = externalStorageDirectory.getAbsolutePath();
            //1.2 获取文件名
            String fileName = editName.getText().toString();
            //1.3 输出到editValue
            String filePath = externalAbsolutePath+"/"+fileName;
            File file = new File(filePath);
            if(!file.exists()){
                Toast.makeText(this,"文件不存在",Toast.LENGTH_SHORT).show();
                return;
            }
            StringBuilder contentValue = new StringBuilder("");
            FileInputStream fileInputStream = new FileInputStream(filePath);
            byte[] bytes = new byte[1024];
            while (fileInputStream.read(bytes)!=-1){
                contentValue.append(new String(bytes));
            }
            editValue.setText(contentValue.toString());
            fileInputStream.close();
        }
    }

    /**
     * 将数据保存到/mnt/sdcard/Android/data/package_name/files下面
     * @param view
     */
    public void save2(View view) throws IOException {
        //判断是否拥有权限
        if(ContextCompat.checkSelfPermission(SdActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(SdActivity.this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},3);
        }else{
            save2Method();
        }
    }

    public void save2Method() throws IOException {
        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            //保存数据到/mnt/sdcard/Android/data/package_name/files下面
            File externalFilesDir = getExternalFilesDir(null);
            if(!externalFilesDir.exists()){
                externalFilesDir.mkdir();
            }
            //1.2 获取文件名和内容
            String fileName = editName.getText().toString();
            String fileContent = editValue.getText().toString();
            //1.3 保存
            String filePath = externalFilesDir.getAbsolutePath()+"/"+fileName;
            FileOutputStream fileOutputStream = new FileOutputStream(filePath);
            byte[] contentBytes = fileContent.getBytes();
            fileOutputStream.write(contentBytes);
            fileOutputStream.flush();
            fileOutputStream.close();
            Toast.makeText(this,"保存成功",Toast.LENGTH_SHORT).show();
        }
    }


    /**
     * 读取/mnt/sdcard/Android/data/package_name/files数据
     * @param view
     */
    public void read2(View view) throws IOException {
        //判断是否拥有权限
        if(ContextCompat.checkSelfPermission(SdActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(SdActivity.this,new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},4);
        }else{
            read2Method();
        }
    }

    public void read2Method() throws IOException {
        //读取sdcard数据
        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            //1 获取sdcard存储路径
            File externalStorageDirectory = getExternalFilesDir(null);
            if(!externalStorageDirectory.exists()){
                Toast.makeText(this,"文件夹不存在",Toast.LENGTH_SHORT).show();
                return;
            }
            String externalAbsolutePath = externalStorageDirectory.getAbsolutePath();
            //1.2 获取文件名
            String fileName = editName.getText().toString();
            //1.3 输出到editValue
            String filePath = externalAbsolutePath+"/"+fileName;
            File file = new File(filePath);
            if(!file.exists()){
                Toast.makeText(this,"文件不存在",Toast.LENGTH_SHORT).show();
                return;
            }
            StringBuilder contentValue = new StringBuilder("");
            FileInputStream fileInputStream = new FileInputStream(filePath);
            byte[] bytes = new byte[1024];
            while (fileInputStream.read(bytes)!=-1){
                contentValue.append(new String(bytes));
            }
            editValue.setText(contentValue.toString());
            fileInputStream.close();
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode){
            case 1:
                if(grantResults.length>0&&grantResults[0]== PackageManager.PERMISSION_GRANTED){
                    try {
                        save1Method();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }else {
                    Toast.makeText(this,"You denied the permission",Toast.LENGTH_SHORT).show();
                }
                break;
            case 2:
                if(grantResults.length>0&&grantResults[0]==PackageManager.PERMISSION_GRANTED){
                    try {
                        read1Method();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }else {
                    Toast.makeText(this,"You denied the permission",Toast.LENGTH_SHORT).show();
                }
                break;

            case 3:
                if(grantResults.length>0&&grantResults[0]==PackageManager.PERMISSION_GRANTED){
                    try {
                        save2Method();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }else {
                    Toast.makeText(this,"You denied the permission",Toast.LENGTH_SHORT).show();
                }
                break;

            case 4:
                if(grantResults.length>0&&grantResults[0]==PackageManager.PERMISSION_GRANTED){
                    try {
                        read2Method();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }else {
                    Toast.makeText(this,"You denied the permission",Toast.LENGTH_SHORT).show();
                }
                break;
            default:
        }
    }
}
